#include <bits/stdc++.h>

using namespace std;

class Solution
{
public:
    int scheduleCourse(vector<vector<int>> &courses)
    {
        sort(courses.begin(), courses.end(), [](vector<int> &a, vector<int> &b)
             { return a[1] < b[1]; });
        priority_queue<int> heap;
        int total_time = 0;
        for (auto &course : courses)
        {
            int time = course[0], duration = course[1];
            if (total_time + time <= duration){
                total_time += time;
                heap.push(time);
            }else if (!heap.empty() && heap.top() > time)
            {
                total_time -= heap.top()- time;
                heap.pop();
                heap.push(time);
            }
        }
        return heap.size();
    }
};